<?php
class Activity extends EventfulAppModel {

    public $name = 'Activity';
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * add activities based on the user specified data
     * @param array $user
     * @param string $content, may be an template
     * @url object
     */
    public function add($options = array()){
        $options = array_merge(array_flip(array('user', 'content', 'url', 'params')), $options);
        extract($options);
        $name = empty($user['name']) ? '' : (empty($user['username']) ? $user['name'] : $user['username']);
        if(!empty($url)){
            $url = array_merge(array(
                'controller'=>null,
                'action' => 'view'
            ), (array)$url);
        }
        $params = array_merge(array('user'=>$name), (array)$params);
        $data = array(
            'Activity'=> array(
                'user_id' => empty($user['id']) ? 0 : $user['id'],
                'content' => String::insert($content, $params),
                'url' => json_encode($url)
            )
        );
        return $this->save($data);
    }

    /**
     * Find latest Activities with the user specified search conditions
     * @param: int $limit
     * @return: results
     */
    public function latestActivities($options=array()){
        $_options = array(
            'limit'=>10,
            'order' => 'Activitycreated DESC'
        );
        $options = array_merge($_options, $options);
        return $this->find('all', $options);
    }

    /**
     * Find Activities that happens on an specified user
     * @param: int $user_id
     * @param: array $options
     * @return: search results
     */
    public function userActivities($user_id=null, $options=array()){
        $_options = array(
            'limit' => 10,
            'order' => 'Activity.created DESC',
            'conditions' => array('Activity.user_id'=>$user_id)
        );
        $options = array_merge_recursive($_options, $options);
        return $this->find('all', $options);
    }

}
?>